<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="菜单计划名称" prop="menuPlanName">
        <el-input
          v-model="queryParams.menuPlanName"
          placeholder="请输入菜单计划名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单执行时间" prop="rangeTime">
        <el-date-picker clearable
          v-model="queryParams.rangeTime"
          type="daterange"
          range-separator="至"
          value-format="YYYY-MM-DD"
          start-placeholder="菜单开始时间"
          end-placeholder="菜单结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:menuPlan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:menuPlan:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:menuPlan:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="menuPlanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" prop="menuPlanId" width="50" />
      <el-table-column label="菜单计划名称" align="center" prop="menuPlanName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="菜单执行时间" align="center" prop="startTime" width="140">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="菜单结束时间" align="center" prop="endTime" width="140">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划进度" align="center" prop="endTime" width="100">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.endTime)">{{ calculateRemainDays(scope.row.endTime) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:menuPlan:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:menuPlan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改菜单计划对话框 -->
    <el-drawer :title="title" v-model="open" width="500px" append-to-body direction="rtl" size="50%"> 
      <el-form ref="menuPlanRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="菜单计划名称" prop="menuPlanName">
          <el-input v-model="form.menuPlanName" placeholder="请输入菜单计划名称" />
        </el-form-item>
        <el-form-item label="菜单执行时间" prop="rangeTime">
          <el-date-picker clearable
            v-model="form.rangeTime"
            type="daterange"
            range-separator="至"
            value-format="YYYY-MM-DD"
            start-placeholder="菜单开始时间"
            end-placeholder="菜单结束时间"
            :disabled-date="disabledDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入内容" />
        </el-form-item>
        <el-tabs type="border-card" stretch>
          <el-tab-pane label="周一">
            <editor v-model="form.menuPlanMon" :min-height="200"/>
          </el-tab-pane>
          <el-tab-pane label="周二">
            <editor v-model="form.menuPlanTue" :min-height="200"/>
          </el-tab-pane>
          <el-tab-pane label="周三">
            <editor v-model="form.menuPlanWed" :min-height="200"/>
          </el-tab-pane>
          <el-tab-pane label="周四">
            <editor v-model="form.menuPlanThur" :min-height="200"/>
          </el-tab-pane>
          <el-tab-pane label="周五">
            <editor v-model="form.menuPlanFri" :min-height="200"/>
          </el-tab-pane>
          <el-tab-pane label="周六">
            <editor v-model="form.menuPlanSat" :min-height="200"/>
          </el-tab-pane>
          <el-tab-pane label="周日">
            <editor v-model="form.menuPlanSun" :min-height="200"/>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="MenuPlan">
import { listMenuPlan, getMenuPlan, delMenuPlan, addMenuPlan, updateMenuPlan } from "@/api/manage/menuPlan";

const { proxy } = getCurrentInstance();

const menuPlanList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    menuPlanName: null,
    rangeTime: [],
  },
  rules: {
    menuPlanName: [
      { required: true, message: "菜单计划名称不能为空", trigger: "blur" }
    ],
    rangeTime: [
      { required: true, message: "请选择时间范围", trigger: "change" },
      { validator: validateRangeTime, trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询菜单计划列表 */
function getList() {
  loading.value = true;
  listMenuPlan(queryParams.value).then(response => {
    menuPlanList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    menuPlanId: null,
    menuPlanName: null,
    // menuPlanMon: undefined,
    // menuPlanTue: undefined,
    // menuPlanWed: undefined,
    // menuPlanThur: undefined,
    // menuPlanFri: undefined,
    // menuPlanSat: undefined,
    // menuPlanSun: undefined,
    createTime: null,
    startTime: null,
    endTime: null,
    rangeTime: [],
    remark: null,
    userId: null
  };
  proxy.resetForm("menuPlanRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.menuPlanId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
// 修改handleAdd函数
function handleAdd() {
  reset();
  // 设置默认时间为今天开始的7天
  const today = new Date();
  const endDate = new Date();
  endDate.setDate(today.getDate() + 6); // 6天后就是7天范围
  
  form.value.rangeTime = [
    proxy.parseTime(today, '{y}-{m}-{d}'),
    proxy.parseTime(endDate, '{y}-{m}-{d}')
  ];
  
  open.value = true;
  title.value = "添加菜单计划";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _menuPlanId = row.menuPlanId || ids.value
  getMenuPlan(_menuPlanId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改菜单计划";
  });
}
// 修改时间范围校验函数
function validateRangeTime(rule, value, callback) {
  if (value && value.length === 2) {
    const [start, end] = value;
    const startDate = new Date(start);
    const endDate = new Date(end);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // 检查起始时间是否为今天
    const isStartToday = startDate.toDateString() === today.toDateString();
    
    if (!isStartToday) {
      callback(new Error("起始时间必须为今天"));
    } else if (startDate > endDate) {
      callback(new Error("结束时间不能早于开始时间"));
    } else if (Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1 !== 7) {
      callback(new Error("必须选择正好7天的时间范围"));
    } else {
      callback();
    }
  } else {
    callback();
  }
}

// 修改提交表单函数中的校验部分
function submitForm() {
  proxy.$refs["menuPlanRef"].validate(valid => {
    if (valid) {
      // 确保时间范围是7天且起始时间为今天
      if (form.value.rangeTime && form.value.rangeTime.length === 2) {
        const [start, end] = form.value.rangeTime;
        const startDate = new Date(start);
        const endDate = new Date(end);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        // 检查起始时间是否为今天
        if (startDate.toDateString() !== today.toDateString()) {
          proxy.$modal.msgError("起始时间必须为今天");
          return;
        }
        
        // 设置开始和结束时间
        form.value.startTime = start;
        form.value.endTime = end;
      }

      if (form.value.menuPlanId != null) {
        updateMenuPlan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMenuPlan(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _menuPlanIds = row.menuPlanId || ids.value;
  const delName = _menuPlanIds.length >= 1 ? '选中的菜单计划' : row.menuPlanName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function() {
    return delMenuPlan(_menuPlanIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/menuPlan/export', {
    ...queryParams.value
  }, `menuPlan_${new Date().getTime()}.xlsx`)
}

// 计算剩余天数
function calculateRemainDays(endTime) {
  if (!endTime) return 'N/A';
  
  const endDate = new Date(endTime);
  const now = new Date();
  const timeDiff = endDate - now;
  
  // 如果已经过期
  if (timeDiff < 0) return '已结束';
  
  // 计算剩余天数并保留一位小数
  const remainDays = (timeDiff / (1000 * 60 * 60 * 24)).toFixed(1);
  return `${remainDays}天`;
}

// 获取tag类型
function getTagType(endTime) {
  if (!endTime) return 'info';
  
  const endDate = new Date(endTime);
  const now = new Date();
  const timeDiff = endDate - now;
  
  // 如果已经过期
  if (timeDiff < 0) return 'danger';
  
  return 'primary';
}

// 添加disabledDate函数
function disabledDate(time) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time < today;
}

getList();
</script>
